$(function () {
    getCateList();
    // 封装 页面渲染
    function getCateList() {
        $.ajax({
            url: '/admin/category/list',
            type: 'get',
            dataType: 'json',
            success: (res) => {
                // console.log(res);
                let htmlStr = template('a1', res)
                $("tbody").html(htmlStr);
            }
        })
    }
    let layer = layui.layer;
    let form = layui.form;
    // 添加分类按钮
    let indexAdd = null
    $("#btnAdd").on("click", function () {
        indexAdd = layer.open({
            type: 1,
            title: '添加文章分类',
            area: ['500px', '260px'],
            content: $('#dialog-add').html()
        })
    })
    // 添加分类 表单提交
    $("body").on("submit", "#form-add", function (e) {
        e.preventDefault();
        $.ajax({
            url: '/admin/category/add',
            type: 'post',
            data: $(this).serialize(),
            success: (res) => {
                // console.log(res);
                layer.close(indexAdd);
                getCateList();
            }
        })
    })

    // 删除
    $("tbody").on("click", ".btn-delete", function () {
        let id = $(this).attr("data-id");
        // console.log(id);

        $.ajax({
            url: '/admin/category/delete',
            type: 'post',
            data: {
                id: id
            },
            success: (res) => {
                // console.log(res);
                if (res.code !== 200) {
                    return layer.msg(res.msg)
                }
                layer.msg("恭喜您, 删除文章分类成功!", {
                    icon: 6
                })
                getCateList();
            }
        })
    })


    // 编辑按钮
    let indexEdit = null;
    $("tbody").on("click", "#btn-edit", function () {
        let id = $(this).attr("data-id")
        indexEdit = layer.open({
            type: 1,
            title: '修改文章分类',
            area: ['500px', '260px'],
            content: $('#dialog-edit').html()
        })
        $.ajax({
            url: '/admin/category/search',
            type: 'get',
            data: {
                id
            },
            dataType: 'json',
            success: (res) => {
                console.log(res.data);
                form.val('form-edit', res.data[0])
            }
        })

    })

    // 确认修改
    $("body").on("submit", "#form-edit", function (e) {
        e.preventDefault();
        $.ajax({
            url: '/admin/category/edit',
            type: 'post',
            data: $(this).serialize(),
            success: (res) => {
                // console.log(res);
                if (res.code !== 200) {
                    return layer.msg(res.msg, {
                        icon: 5
                    })
                }
                layer.msg("恭喜您,编辑文章类别成功!", {
                    icon: 6
                })
                layer.close(indexEdit);
                getCateList();
            }
        })
    })
})